package tree;

public class BinaryTree <T>{
    private int  id;
    private T data;
    private BinaryTree left;
    private BinaryTree right;

    public BinaryTree(){}
    public BinaryTree(int id){
        this.id = id;
    }
    public BinaryTree(int id,T data){
        this.id = id;
        this.data = data;
    }

    //前序遍历
    public static void prefixOrder(BinaryTree treeNode){
        if (treeNode == null){
            return;
        }
        System.out.print(treeNode.id);
        prefixOrder(treeNode.left);
        prefixOrder(treeNode.right);

    }
    //前序遍历查找
    public static BinaryTree searchPreOrder(BinaryTree treeNode,int target){
        if (treeNode.id == target){
            return treeNode;
        }
        BinaryTree temp = new BinaryTree();
        if (treeNode.left != null){
            temp = searchPreOrder(treeNode.left,target);
        }
        if (temp.id == target){
            return temp;
        }
        if (treeNode.right != null){
            temp = searchPreOrder(treeNode.right,target);
        }
        return temp;
    }

    //中序遍历
    public static void midOrder(BinaryTree treeNode){
        if (treeNode == null){
            return;
        }
        midOrder(treeNode.left);
        System.out.print(treeNode.id);
        midOrder(treeNode.right);
    }



    //后序遍历
    public static void suffixOrder(BinaryTree treeNode){
        if (treeNode == null){
            return;
        }
        suffixOrder(treeNode.left);
        suffixOrder(treeNode.right);
        System.out.print(treeNode.id);
    }

    public static void main(String[] args) {
        BinaryTree tree1 = new BinaryTree(1,"sodug");
        BinaryTree tree2 = new BinaryTree(2,"saj");
        BinaryTree tree3 = new BinaryTree(3,"labsd");
        BinaryTree tree4 = new BinaryTree(4,"aosdfb");
        BinaryTree tree5 = new BinaryTree(5,"saigo");
        BinaryTree tree6 = new BinaryTree(6,"sad");
        BinaryTree tree7 = new BinaryTree(7,"sidah");

        tree1.left = tree2;
        tree1.right = tree3;
        tree2.right = tree4;
        tree3.left = tree5;
        tree3.right = tree6;
        tree6.left = tree7;

        prefixOrder(tree1);
        System.out.println();
        midOrder(tree1);
        System.out.println();
        suffixOrder(tree1);

        System.out.println("============================================");
        BinaryTree tree = searchPreOrder(tree1, 5);
        System.out.println(tree.data);
    }
}

